package waggle.client;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;

public class PopUpImgShow extends Composite {

    AbsolutePanel ap;
    int popUpSizeX;
    int popUpSizeY;
    AbsolutePanel imgPanel;
    int imgPanelSizeX;
    int imgPanelSizeY;
    AbsolutePanel bottomPanel;

    String []imgName;
    String []imgFile;
    String []imgComment;
    int imgStart;                           // image id from to start.
    String imgPath;                         // images path
    ImagePopUp img;                         // image which will be shown.

    Image next;
    Image previous;
    Image close;


    Label lImgName;                         // image name
    Label lImgComment;                      // image comment

    int currentImg;

    /* add a loading message                */
    String loading;
    Label loadingLabel;
    int ind = 1;
    Timer t;

    /* cache the next and previous image            */
    Image imgCacheN;
    Image imgCacheP;


    //Button play;                          // button AUTO PLAY
    Image play;
    private boolean playFlag = true;
    private boolean autoPlayOn = false;
    Timer tPlay;
    private Label playMode;

    
    /**
     * Method to add image to the panel.
     * Because the image size method from the image class can't return the values
     * until the image is fully loaded by browser, this method add the image
     * on the popup panel's bottom right corner (making the image invisible and
     * creating the background loading effect). When the image is complete downloaded,
     * get the image's size and the it's added to the popup panel.
     * 每一個要加入的image,最後都是靠scaleImg加入
     * 真正加入之前,也會啟動clearImg,把視窗清空
     */
    private void addImage(String imagePath){
            showLoadingProcess(true);
            //img = new ImagePopUp(imagePath, this);
            //imgPanel.add(img, imgPanelSizeX, imgPanelSizeY);
            Image img2 = new Image();
            img2.setUrl( imagePath );
            img2.setWidth("300px");
            img2.setHeight("300px");
//            imgPanel.add(img2, imgPanelSizeX, imgPanelSizeY);
            scaleImg(img2);
    }

    /**
     * scale the image to fit the panel
     */
    public void scaleImg(Image im){
            showLoadingProcess(false);

/*
            int iox = im.getWidth();
            int ioy = im.getHeight();

            float scaleX = (float)imgPanelSizeX/iox;
            float scaleY = (float)imgPanelSizeY/ioy;

            float scalef = scaleX<=scaleY ? scaleX:scaleY;
            int ix = (int)(iox*scalef);
            int iy = (int)(ioy*scalef);
            img.setPixelSize(ix, iy);
*/
            lImgName.setText(imgName[currentImg]);
            lImgComment.setText(imgComment[currentImg]);

            clearImg();
            //imgPanel.add(img, (imgPanelSizeX-ix)/2, (imgPanelSizeY-iy)/2);
            imgPanel.add(im);

            getNextAndPrevious(currentImg); // cache the next and previous pictures;
    }
    
    /**
     * Method to clear the old image before add the new one.
     */
    private void clearImg(){
            imgPanel.clear();
    }
    
    
    

    //呼叫addImage時機有三個,前面兩個很固定,就是由按鈕和autoplay啟動
    //最後一個則是,啟動就包含在裡面
    
    /**
     * Method to show the previous image.
     */
    public void previousImg(){
            showLoadingProcess(false);
            if(currentImg>0){
                    currentImg--;
                    checkButtons(currentImg);
                    addImage(imgPath+imgFile[currentImg]);
            }
    }
    
    /**
     * Method to show the next image.
     */
    public void nextImg(){
            showLoadingProcess(false);
            if(currentImg<(imgFile.length-1)){
                    currentImg++;
                    checkButtons(currentImg);
                    addImage(imgPath+imgFile[currentImg]);
            }
    }

    /**
     * Initialize
     */
    private void initialize(){
//k            setGlassStyleName("gwt-PopupPanelGlass");
//k            setGlassEnabled(true);

            getMaximSquareSize();

//k            setPosition();

            ap = new AbsolutePanel();
            ap.setPixelSize(popUpSizeX, popUpSizeY);
            ap.setStyleName("popUpPanel");

            imgPanel = new AbsolutePanel();
            imgPanelSizeX = popUpSizeX-40;
            imgPanelSizeY = popUpSizeY-40;
            imgPanel.setPixelSize(imgPanelSizeX, imgPanelSizeY);
            ap.add(imgPanel, 20,1);

            bottomPanel = new AbsolutePanel();
            bottomPanel.setPixelSize(popUpSizeX, 50);

            next = new Image("ext/next.gif");
            next.addClickHandler(new ClickHandler() {
                    public void onClick(ClickEvent event) {
                            if(!playFlag){autoPlay(false);play.setUrl("ext/play.gif");playFlag = true;}
                            nextImg();}} );
            bottomPanel.add(next, popUpSizeX-110, 5);

            previous = new Image("ext/previous.gif");
            previous.addClickHandler(new ClickHandler() {
                    public void onClick(ClickEvent event) {
                            if(!playFlag){autoPlay(false);play.setUrl("ext/play.gif");playFlag = true;}
                            previousImg();}} );
            bottomPanel.add(previous, popUpSizeX-160, 5);

            close = new Image("ext/close.gif");
            close.addClickHandler(new ClickHandler() {
                    public void onClick(ClickEvent event) {
                            closeImg();}} );
            bottomPanel.add(close, popUpSizeX-40, 5);

            play = new Image("ext/play.gif");
            play.addClickHandler(new ClickHandler() {
                    public void onClick(ClickEvent event) {
                            if(playFlag && currentImg < imgFile.length-1){
                                    autoPlay(true);
                                    play.setUrl("ext/pause.gif");
                                    playFlag = false;
                            }
                            else{
                                    stopAutoPlay();
                            }
                            }} );
            bottomPanel.add(play, popUpSizeX-240, 5);

            lImgName = new Label();
            bottomPanel.add(lImgName, 20,0);

            lImgComment = new Label();
            bottomPanel.add(lImgComment, 20,20);


            loading = "Loading...";
            loadingLabel = new Label();
            loadingLabel.setText(loading);
            bottomPanel.add(loadingLabel, popUpSizeX/2,2);

            playMode = new Label();
            bottomPanel.add(playMode, popUpSizeX/2,22);

            ap.add(bottomPanel, 1, popUpSizeY-40);

//k            setWidget(ap);
            initWidget(ap);

            addImage(imgPath+imgFile[imgStart]);

            checkStartImg();
    }
    
    public PopUpImgShow(int imgStart, String imgPath, String []imgFile, String []imgName,  String []imgComment){
            super();

            this.imgStart = imgStart;
            this.imgPath = imgPath;
            this.imgName = imgName;
            this.imgFile = imgFile;
            this.imgComment = imgComment;

            currentImg = imgStart;
            initialize();
    }
    
    //附屬功能
    private void stopAutoPlay(){
            autoPlay(false);
            play.setUrl("ext/play.gif");
            playFlag = true;
    }

    /**
     * Method to check if the selected image is first or the last from album;
     * disable the buttons according.
     * @param id image id
     * 決定是不是最後一張
     */
    private void checkButtons(int id){
            next.setVisible(true);
            previous.setVisible(true);
            if(id==(imgFile.length-1)){next.setVisible(false);
                    if(autoPlayOn){stopAutoPlay();playMode.setText("Last Picture");}
            }
            if(id==0) previous.setVisible(false);
    }

    /**
     * check if the image is first or the last.
     * disable the button according.
     */
    private void checkStartImg(){
            checkButtons(currentImg);
    }

    /**
     * Method to close the popup.
     */
    public void closeImg(){
            if(autoPlayOn)
            	autoPlay(false);
//            this.hide();
    }

    /**
     * Method to get the maxim popup size. The dimension should be the same (square).
     */
    private void getMaximSquareSize(){
//            getWindowSize();
//            int maxX = getBrowserWindowWidth();
//            int maxY = getBrowserWindowHeight();

            int maxX = 500;
            int maxY = 500;
            
            if(maxX<=maxY){
                    popUpSizeX = maxY;
                    popUpSizeY = maxY;
            }
            else{
                    popUpSizeY = maxY;
                    if(maxX>maxY*1.33) popUpSizeX = (int) (maxY*1.33);
                    else popUpSizeX = maxX;
            }

            popUpSizeX-=30;
            popUpSizeY-=30;
//            setSizeX(popUpSizeX);
//            setSizeY(popUpSizeY);
    }
    
    /**
     * This method shows the picture's loading process.
     */
    private void showLoadingProcess(boolean show){
            if(show){
                    // show the loading bar

                    ind = 1;
                    loadingLabel.setText(loading.substring(0, ind));

                    t = new Timer() {
                          @Override
                          public void run() {
                              if(ind<loading.length()){
                                                    ind++;
                                            }
                                            else{
                                                    ind=1;
                                            }
                                            loadingLabel.setText(loading.substring(0, ind));
                          }
                        };
                        //t.schedule(500);
                        t.scheduleRepeating(500);
            }
            else{
                    // hide the loading bar
                    t.cancel();
                    loadingLabel.setText("");
            }
    }

    /**
     * Cache the next and previous pictures to reduce the loading time.
     * @param i picture id
     */
    private void getNextAndPrevious(int i){
            if(i<imgFile.length-1)imgCacheN = new Image(imgPath+imgFile[i+1]);
            if(i>0)imgCacheP = new Image(imgPath+imgFile[i-1]);
    }

    /**
     * AutoPlay method.
     * @param flag
     * 活用了timer功能
     */
    private void autoPlay(boolean flag){
            autoPlayOn = flag;
            if(flag){
                    playMode.setText("Auto Play Mode");
                    tPlay = new Timer() {
                          @Override
                          public void run() {
                              nextImg();
                          }
                        };
                        tPlay.scheduleRepeating(8000);      // wait 8 seconds between pictures.
            }
            else{
                    playMode.setText("");
                    tPlay.cancel();
            }
    }
	
}
